<template>
  <div class="message-list" ref="messageListRef">
    <div class="message-container" :class="containerClasses">
      <!-- 消息列表 -->
      <div v-if="hasMessages" class="messages">
        <transition-group name="message" tag="div" class="message-group">
          <MessageItem
            v-for="message in messages"
            :key="message.id"
            :message="message"
            :is-streaming="isStreaming && message.id === streamingMessageId"
            :show-timestamp="showTimestamp"
            :show-avatar="showAvatar"
            @action="handleMessageAction"
            @retry="handleRetry"
            @copy="handleCopy"
            @delete="handleDelete"
          />
        </transition-group>
        
        <!-- 正在输入指示器 -->
        <transition name="fade">
          <div v-if="isStreaming && !streamingMessageId" class="typing-indicator">
            <div class="typing-content">
              <div class="avatar">
                <el-icon><Robot /></el-icon>
              </div>
              <div class="typing-animation">
                <div class="typing-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <span class="typing-text">AI正在思考中...</span>
              </div>
            </div>
          </div>
        </transition>
      </div>
      
      <!-- 空状态 -->
      <div v-else class="empty-state">
        <div class="empty-content">
          <div class="empty-icon">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <h3 class="empty-title">开始您的智能对话</h3>
          <p class="empty-description">
            我是您的AI助手，可以帮您解答问题、分析数据、处理任务等。
            <br>请在下方输入您的问题开始对话。
          </p>
          <div class="empty-features">
            <div class="feature-item">
              <el-icon><ChatDotRound /></el-icon>
              <span>智能问答</span>
            </div>
            <div class="feature-item">
              <el-icon><List /></el-icon>
              <span>任务分解</span>
            </div>
            <div class="feature-item">
              <el-icon><Connection /></el-icon>
              <span>服务调用</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 滚动到底部按钮 -->
    <transition name="slide-up">
      <el-button
        v-if="showScrollButton"
        type="primary"
        :icon="ArrowDown"
        @click="scrollToBottom"
        class="scroll-to-bottom"
        circle
      />
    </transition>
    
    <!-- 消息统计 -->
    <div v-if="showStats && hasMessages" class="message-stats">
      <span class="stat-item">
        <el-icon><ChatDotRound /></el-icon>
        {{ messageStats.total }} 条消息
      </span>
      <span class="stat-item">
        <el-icon><User /></el-icon>
        {{ messageStats.user }} 条问题
      </span>
      <span class="stat-item">
        <el-icon><Robot /></el-icon>
        {{ messageStats.assistant }} 条回复
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ChatMessage } from '@/types'
import MessageItem from './MessageItem.vue'

// Props
interface Props {
  messages: ChatMessage[]
  isStreaming?: boolean
  streamingMessageId?: string | null
  showTimestamp?: boolean
  showAvatar?: boolean
  showStats?: boolean
  autoScroll?: boolean
  maxHeight?: string
}

const props = withDefaults(defineProps<Props>(), {
  isStreaming: false,
  streamingMessageId: null,
  showTimestamp: true,
  showAvatar: true,
  showStats: false,
  autoScroll: true,
  maxHeight: '100%'
})

// Emits
interface Emits {
  messageAction: [action: string, messageId: string]
  retry: [messageId: string]
  copy: [messageId: string]
  delete: [messageId: string]
}

const emit = defineEmits<Emits>()

// 状态
const messageListRef = ref<HTMLElement>()
const showScrollButton = ref(false)
const isUserScrolling = ref(false)
const scrollTimer = ref<NodeJS.Timeout>()

// 计算属性
const hasMessages = computed(() => props.messages.length > 0)

const containerClasses = computed(() => ({
  'message-container': true,
  'message-container--empty': !hasMessages.value,
  'message-container--streaming': props.isStreaming
}))

const messageStats = computed(() => {
  const stats = {
    total: props.messages.length,
    user: props.messages.filter(msg => msg.role === 'user').length,
    assistant: props.messages.filter(msg => msg.role === 'assistant').length,
    system: props.messages.filter(msg => msg.role === 'system').length
  }
  return stats
})

// 方法
const handleMessageAction = (action: string, messageId: string) => {
  emit('messageAction', action, messageId)
}

const handleRetry = (messageId: string) => {
  emit('retry', messageId)
}

const handleCopy = (messageId: string) => {
  emit('copy', messageId)
}

const handleDelete = (messageId: string) => {
  emit('delete', messageId)
}

const scrollToBottom = (smooth = true) => {
  if (!messageListRef.value) return
  
  const scrollElement = messageListRef.value
  const scrollTop = scrollElement.scrollHeight - scrollElement.clientHeight
  
  if (smooth) {
    scrollElement.scrollTo({
      top: scrollTop,
      behavior: 'smooth'
    })
  } else {
    scrollElement.scrollTop = scrollTop
  }
  
  showScrollButton.value = false
}

const checkScrollPosition = () => {
  if (!messageListRef.value) return
  
  const element = messageListRef.value
  const threshold = 100 // 距离底部100px时显示按钮
  const isNearBottom = element.scrollHeight - element.scrollTop - element.clientHeight < threshold
  
  showScrollButton.value = !isNearBottom && hasMessages.value
}

const handleScroll = () => {
  isUserScrolling.value = true
  
  // 清除之前的定时器
  if (scrollTimer.value) {
    clearTimeout(scrollTimer.value)
  }
  
  // 检查滚动位置
  checkScrollPosition()
  
  // 500ms后认为用户停止滚动
  scrollTimer.value = setTimeout(() => {
    isUserScrolling.value = false
  }, 500)
}

const autoScrollToBottom = () => {
  if (props.autoScroll && !isUserScrolling.value) {
    nextTick(() => {
      scrollToBottom(true)
    })
  }
}

// 监听消息变化，自动滚动到底部
watch(() => props.messages.length, () => {
  autoScrollToBottom()
})

// 监听流式消息变化
watch(() => props.isStreaming, (streaming) => {
  if (streaming) {
    autoScrollToBottom()
  }
})

// 监听消息内容变化（流式更新）
watch(() => {
  const lastMessage = props.messages[props.messages.length - 1]
  return lastMessage?.content
}, () => {
  if (props.isStreaming) {
    autoScrollToBottom()
  }
}, { flush: 'post' })

// 生命周期
onMounted(() => {
  if (messageListRef.value) {
    messageListRef.value.addEventListener('scroll', handleScroll, { passive: true })
    
    // 初始滚动到底部
    nextTick(() => {
      scrollToBottom(false)
    })
  }
})

onUnmounted(() => {
  if (messageListRef.value) {
    messageListRef.value.removeEventListener('scroll', handleScroll)
  }
  
  if (scrollTimer.value) {
    clearTimeout(scrollTimer.value)
  }
})

// 暴露方法
defineExpose({
  scrollToBottom,
  checkScrollPosition
})
</script>

<style lang="scss" scoped>
.message-list {
  position: relative;
  height: 100%;
  overflow: hidden;
}

.message-container {
  height: 100%;
  overflow-y: auto;
  @include scrollbar;
  
  &.message-container--empty {
    @include flex-center;
  }
  
  &.message-container--streaming {
    .message-item:last-child {
      .message-content {
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          right: 0;
          bottom: 0;
          width: 2px;
          height: 1.2em;
          background: var(--primary-color);
          animation: blink 1s infinite;
        }
      }
    }
  }
}

// 消息组
.messages {
  padding: var(--spacing-md);
  min-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.message-group {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

// 正在输入指示器
.typing-indicator {
  @include flex-start;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm) 0;
  opacity: 0.8;
}

.typing-content {
  @include flex-start;
  gap: var(--spacing-sm);
}

.avatar {
  @include avatar(32px);
  @include flex-center;
  background: var(--primary-color-lighter);
  color: var(--primary-color);
  flex-shrink: 0;
}

.typing-animation {
  @include flex-start;
  gap: var(--spacing-sm);
  flex-direction: column;
}

.typing-dots {
  @include flex-start;
  gap: 4px;
  
  span {
    width: 6px;
    height: 6px;
    background: var(--text-color-secondary);
    border-radius: 50%;
    animation: typing 1.4s infinite;
    
    &:nth-child(1) { animation-delay: 0ms; }
    &:nth-child(2) { animation-delay: 200ms; }
    &:nth-child(3) { animation-delay: 400ms; }
  }
}

.typing-text {
  font-size: var(--font-size-small);
  color: var(--text-color-secondary);
}

// 空状态
.empty-state {
  @include flex-center;
  padding: var(--spacing-xl);
  text-align: center;
}

.empty-content {
  max-width: 500px;
}

.empty-icon {
  font-size: 64px;
  color: var(--text-color-placeholder);
  margin-bottom: var(--spacing-lg);
}

.empty-title {
  font-size: var(--font-size-large);
  color: var(--text-color-primary);
  margin-bottom: var(--spacing-md);
  font-weight: 600;
}

.empty-description {
  font-size: var(--font-size-base);
  color: var(--text-color-secondary);
  line-height: 1.6;
  margin-bottom: var(--spacing-lg);
}

.empty-features {
  @include flex-center;
  gap: var(--spacing-lg);
  flex-wrap: wrap;
}

.feature-item {
  @include flex-center;
  gap: var(--spacing-xs);
  color: var(--text-color-secondary);
  font-size: var(--font-size-small);
  
  .el-icon {
    color: var(--primary-color);
  }
}

// 滚动到底部按钮
.scroll-to-bottom {
  position: absolute;
  bottom: var(--spacing-lg);
  right: var(--spacing-lg);
  z-index: var(--z-index-normal);
  box-shadow: var(--box-shadow-base);
  
  &:hover {
    transform: scale(1.1);
  }
}

// 消息统计
.message-stats {
  position: absolute;
  top: var(--spacing-sm);
  right: var(--spacing-sm);
  @include flex-center;
  gap: var(--spacing-sm);
  padding: var(--spacing-xs) var(--spacing-sm);
  background: rgba(255, 255, 255, 0.9);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-extra-small);
  color: var(--text-color-secondary);
  backdrop-filter: blur(4px);
  border: 1px solid var(--border-color-light);
  
  .stat-item {
    @include flex-center;
    gap: 2px;
    
    .el-icon {
      font-size: 12px;
    }
  }
}

// 动画
@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

// 消息过渡动画
.message-enter-active {
  transition: all 0.3s ease;
}

.message-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.message-leave-active {
  transition: all 0.3s ease;
  position: absolute;
  right: 0;
  left: 0;
}

.message-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.message-move {
  transition: transform 0.3s ease;
}

// 滑入动画
.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from,
.slide-up-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

// 淡入动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 响应式适配
@include respond-to(md) {
  .messages {
    padding: var(--spacing-sm);
  }
  
  .empty-content {
    padding: var(--spacing-md);
  }
  
  .empty-features {
    flex-direction: column;
    gap: var(--spacing-md);
  }
  
  .scroll-to-bottom {
    bottom: var(--spacing-md);
    right: var(--spacing-md);
  }
  
  .message-stats {
    position: static;
    margin: var(--spacing-sm);
    justify-content: center;
  }
}

// 暗色主题
@include dark-theme {
  .message-stats {
    background: rgba(0, 0, 0, 0.8);
    border-color: var(--border-color);
  }
}
</style>